import 'package:flutter/material.dart';
import 'table/resp_result.dart';
import 'util/http_util.dart';
import 'package:dio/dio.dart';
import 'widget/index_item.dart';
import 'ItemInfoDetail.dart';
import 'configure/type.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HaiTao extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return HaitaoWidget();
  }
  
}

class HaitaoWidget extends State<HaiTao>{
  List<RstData> _listData;//设置列表数据
  GlobalKey<ScaffoldState> _globalKeyState=GlobalKey();
  String title="海淘";
  ScrollController _scrollController=ScrollController();
  String type="";
  String typeValue="";
  int pager=1;

  HaitaoWidget(){
    _scrollController.addListener((){
      var pix=_scrollController.position.pixels;
      var max=_scrollController.position.maxScrollExtent;
      if(pix==max){
        //已下拉到底部，调用加载更多方法
        _loadMoreData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(title,style: TextStyle(color: Colors.white),),
        leading: IconButton(
            icon: Icon(Icons.menu,color: Colors.white,),
            onPressed: (){
              _changeDrawer();//切换drawer的关闭打开
            }),
        backgroundColor: Colors.green[500],
      ),
      body: _listInfos(),
    );
  }

  //list列表
  Widget _listInfos(){
    return Scaffold(
      key: _globalKeyState,
      body: RefreshIndicator(
          child: ListView.builder(
            itemCount: _listData==null?0:_listData.length+1,//此处 +1 是为了在最后添加一个progress
            itemBuilder: (content,index){
              return _listItem(index);
            },
            controller: _scrollController,
          ),
          onRefresh: _onRefresh
      ),
      drawer: _setDrawerList(),
    );
  }

  //item
  Widget _listItem(int index){
    if(index==_listData.length){
      return Center(
        child: Container(
          height: 20,
          width: 20,
          margin: EdgeInsets.all(5),
          child: CircularProgressIndicator(
            backgroundColor: Colors.green,
          ),
        ),
      );
    }else{
      RstData data=_listData[index];
      return GestureDetector(
        child: IndexItem(rstData: data,),
        onTap:(){ _itemClick(data);},
      );
    }
  }

  //切换侧边栏的打开与关闭
  void _changeDrawer(){
    if(_globalKeyState.currentState.isDrawerOpen){
      _globalKeyState.currentState.openEndDrawer();
    }else{
      _globalKeyState.currentState.openDrawer();
    }
  }

  //侧边栏列表
  Widget _setDrawerList(){
    var type=haitao_type;
    return Container(
      width: 200,
      color: Colors.white,
      child: ListView.builder(
        itemCount: type.length,
        itemBuilder: (context,index){
          Map<String,String> map=type[index];
          return _drawerItem(map);
        },
      ),
    );
  }
  //侧边栏 item
  Widget _drawerItem(Map<String,String> map){
    if(map["title"]=="=="){
      return Container(
        height: 1,
        decoration: BoxDecoration(
          color: Colors.black54,
        ),
      );
    }else{
      return GestureDetector(
        child: Container(
          height: 35,
          color: Colors.white,
          padding: EdgeInsets.only(left: 5),
          alignment: Alignment.centerLeft,
          child: Text(map["title"]),
        ),
        onTap: (){
          _drawerItemClick(map);
        },
      );
    }
  }
  //侧边栏点击事件
  void _drawerItemClick(Map<String,String> map){
    FormData formData=FormData();
    if(_listData!=null && _listData.length>0){
      formData.add("markid", "${_listData[0].id}");
    }else {
      formData.add("markid", "5685521");
    }
    if(map["type"]=="all"){
      setState(() {
        title = "海淘";
      });
      type="";
    }else {
      setState(() {
        title = "海淘-${map["title"]}";
      });
      type=map["type"];
      if (type == "hot") {
        typeValue="1";
        formData.add("onlyhots", typeValue);
      } else if (type == "mall") {
        typeValue=map["mall"];
        formData.add("mall", typeValue);
      } else if (type == "cate") {
        typeValue=map["cate"];
        formData.add("cate", typeValue);
      }
    }
    pager=1;//页码归一
    _getGuangdiuIndexData(formData);
    _changeDrawer();
  }

  void _itemClick(RstData data){
    Navigator.push(context, MaterialPageRoute(builder: (cx)=>ItemInfoDetail(id: data.id,title: data.title,)));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _onRefresh();
  }

  //加载更多
  void _loadMoreData(){
    FormData formData=FormData();
    Future<int> sinc=_getShareValue("t_sinceid", 5685521).then((id){
      formData.add("sinceid", id);
      if(type!=""){
        formData.add(type, typeValue);
      }
      pager++;
      _getGuangdiuIndexData(formData);
    });
  }

  //下拉刷新
  Future<Null> _onRefresh() async {
    pager=1;
    FormData formData=FormData();
    Future<int> markid=_getShareValue("t_markid", 5685521).then((id){
      formData.add("markid", id);
      _getGuangdiuIndexData(formData);
    });
    return null;
  }

  void _getGuangdiuIndexData(FormData formData) async{
    String url="getlist.php";
    formData.add("country","us");
    Response resp=await HttpUtil().post(url,data: formData).then((resp){
      RespResult respResult=RespResult.fromJson(resp.data);
      var data=_listData;
      if(data==null){
        data=respResult.data;
      }else {
        if (pager == 1) {
          data.clear();
        }
        data.addAll(respResult.data);
      }
      setState(() {
        _listData=data;
      });
      if(pager==1){
        _scrollController.position.moveTo(0);//滑动到最顶端
      }
      if(_listData.length>0){
        _setSharedPerfence("t_markid", _listData[0].id);
        _setSharedPerfence("t_sinceid", _listData[_listData.length-1].id);
      }
    });
  }

  void _setSharedPerfence(String key,int valueId) async{
    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    sharedPreferences.setInt(key, valueId);
  }

  Future<int> _getShareValue(String key,int valueId) async{
    SharedPreferences sharedPreferences= await SharedPreferences.getInstance();
    var p= sharedPreferences.getInt(key);
    print(p);
    if(p==null){
      return valueId;
    }
    return p;
  }
  
}